package com.example.demo.Controller;

import com.example.demo.model.User;
import com.example.demo.model.UserMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Resource
    UserMapper userMapper;
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req){
        User user = userMapper.selectByName(username);
//        去表里查名字
        if(user ==null || !user.getPassword().equals(password)){
            System.out.println("登录失败，用户名或密码错误"+user);
            return new User();
        }
        //登录成功创建对话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        //在返回对象信息时把密码遮盖
        user.setPassword("***");
        return user;

    }
    @PostMapping("/register")
    @ResponseBody  //表示返回的是数据
    public Object register(String username, String password){
        User user = null;
        try{
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            //把user对象插入到数据表中
            int ret = userMapper.insert(user);
            System.out.println("注册ret:"+ret);
            //数据表设置的是unique当名字重复时注册失败，
        }catch (DuplicateKeyException e){
          //抛出异常，返回空白对象
            user =new User();
            System.out.println("注册失败,用户名重复：username= "+username);
        }
        return user;
    }
    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req){
//        先从请求中获取到对话
        HttpSession session =req.getSession(false);
        if(session == null){
//            会话不存在请重新登录，返回一个空对象
            System.out.println("[getUserInfo]当前获取不到session对象");
            return new User();
        }

//        从会话中获取到之前保存的用户对象
        User user =(User) session.getAttribute("user");
        if(user == null){
            System.out.println("[getUserInfo]当前获取不到user对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
